<template>
    <div>
        <div class="title"> §用户管理</div>
        <br>
        <div class="search">
            用户搜索：<input type="text" @input="inputChange" v-model="value" :placeholder="text">
            <el-dropdown class="my_dropdown">
                <span class="el-dropdown-link">
                    类别<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu class="dropdown" slot="dropdown">
                    <el-dropdown-item @click.native="changSort(1)" style="font-size: 12px;">id搜索</el-dropdown-item>
                    <el-dropdown-item @click.native="changSort(2)" style="font-size: 12px;">昵称搜索</el-dropdown-item>
                    <el-dropdown-item @click.native="changSort(3)" style="font-size: 12px;">性别搜索</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
            <button @click="returnAll">返回</button>
            <button @click="searchInfo">搜索</button>
        </div>
        <div >
            <button style="width: 90px;" @click.prevent="delData()" class="bulk-detetion"><i class="el-icon-minus"></i> 批量删除</button>
            <button class="add-info" style="width: 100px;" @click="uploadVisible">
                <i class="el-icon-circle-plus-outline"></i>批量添加 
            </button>
            <button @click="singleAdd" class="single-add"><i class="el-icon-plus"></i>单个增加</button>
            <button class="style-down"><a href="http://124.71.221.237:8080/test/test/体检患者信息录入模板.xlsx"><i class="el-icon-download"></i>模板下载</a></button>
            <button @click="exportUser" class="import-user"><a href="http://124.71.221.237:8080/test/admin/download"><i class="el-icon-upload2"></i> 导出人员</a></button>
        </div>
        <el-dialog
            title="上传文件"
            :visible.sync="dialogVisible1"
            width="30%"
            >
            <el-upload  
                ref="upload"  
                class="upload-demo"  
                accept=".xls, .xlsx"
                action="http://124.71.221.237:8080/test/admin/upload"  
                :on-success="handleSuccess" 
                :before-upload="beforeUpload"  
                :file-list="fileList"  
                :auto-upload="false"  
                :on-change="handleChange"  
            >  
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>  
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>  
                <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件，且不超过500kb</div>  
            </el-upload>  
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible1 = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible1 = false">确 定</el-button>
            </span>
        </el-dialog>  
        <!-- 初始数据渲染 -->
        <el-table
        :data="tableData"
        ref="table"
        tooltip-effect="dark"
        border
        :row-style="{height: '0'}"
        style="width: 100%;"
        @selection-change="selectRow">
            <el-table-column type="selection" width="40" align="center">
            </el-table-column>
            <el-table-column
                class="table-column"
                fixed
                prop="patientId"
                label="ID"
                width="50">
            </el-table-column>
            <el-table-column
                prop="patientName"
                label="昵称"
                width="65">
            </el-table-column>
            <el-table-column
                prop="patientSex"
                label="性别"
                width="50">
            <template slot-scope="scope">
                <span v-if="scope.row.patientSex === '男'"><i style="color:blue" class="el-icon-male"></i></span>
                <span  v-else-if="scope.row.patientSex === '女'"><i style="color:palevioletred" class="el-icon-female"></i></span>
            </template>
            </el-table-column>
            <el-table-column
                prop="patientAge"
                label="年龄"
                width="50">
            </el-table-column>
            <el-table-column
                prop="patientMoney"
                label="余额"
                width="80">
            </el-table-column>            
            <el-table-column
                prop="patientIdCard"
                label="身份证"
                width="170">
            </el-table-column>
            <el-table-column
                prop="patientPhone"
                label="电话号码"
                width="110">
            </el-table-column>
            <el-table-column
                prop="patientHeight"
                label="身高(cm)"
                width="79">
            </el-table-column>
            <el-table-column
                prop="patientWeight"
                label="体重(kg)"
                width="78">
            </el-table-column>
            <el-table-column
                prop="patientCreateTime"
                label="创建时间"
                width="158">
            </el-table-column>
            <el-table-column
            fixed="right"
            label="操作"
            width="100">
                <template slot-scope="scope">
                    <el-button @click="alterClick(scope.row)" type="text" size="small">修改</el-button>
                    <el-button @click="open(scope.row)" style="color:red" type="text" size="small">删除</el-button>
            </template>
            </el-table-column>
        </el-table><!-- 分页 -->
        <el-pagination
            background
            @current-change="handleCurrentChange"  
            :current-page="page.currentPage" 
            :page-size="page.pageSize"
            layout="prev, pager, next"
            :total="page.total"
            >
        </el-pagination>
        
        <!-- 修改人员内容 -->
        <el-dialog 
            title="修改人员信息" 
            :show-close="false"
            :visible.sync="dialogVisible"
            width="500px"
            >
            <el-form ref="nowPatient" status-icon :rules="rules" :model="nowPatient" label-width="80px">
                <el-form-item label="id:" class="custom-item">
                    <div style="float:left">{{nowPatient.patientId}}</div>
                </el-form-item>
                <el-form-item label="昵称:" class="custom-item">
                    <div style="float:left">{{nowPatient.patientName}}</div>
                </el-form-item>
                <el-form-item label="余额" prop="patientMoney" class="custom-item">
                    <el-input v-model="nowPatient.patientMoney"></el-input>
                </el-form-item>
                <el-form-item label="身高(cm)" prop="patientHeight" class="custom-item">
                    <el-input v-model="nowPatient.patientHeight"></el-input>
                </el-form-item>
                <el-form-item label="体重(kg)" prop="patientWeight" class="custom-item">
                    <el-input v-model="nowPatient.patientWeight"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="sureCommit">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 添加 -->
        <el-dialog title="添加用户" width="40%" :visible.sync="dialogFormVisible">
            <el-form label-position="right"  status-icon :rules="rules" ref="form" :model="form">
                <el-form-item label="姓名" prop="name" :label-width="formLabelWidth">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex" :label-width="formLabelWidth">
                    <template>
                        <el-radio v-model="radio" label="1">男</el-radio>
                        <el-radio v-model="radio" label="2">女</el-radio>
                    </template>                
                </el-form-item>
                <el-form-item label="年龄" prop="age" :label-width="formLabelWidth">
                    <el-input v-model="form.age" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone" :label-width="formLabelWidth">
                    <el-input v-model="form.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="身份证号" prop="cardID" :label-width="formLabelWidth">
                    <el-input v-model="form.cardID" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="身高" prop="height" :label-width="formLabelWidth">
                    <el-input v-model="form.height" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="体重" prop="weight" :label-width="formLabelWidth">
                    <el-input v-model="form.weight" autocomplete="off"></el-input>
                </el-form-item>
                
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="resetForm('form')">重 置</el-button>
                <el-button @click="addCommit" type="primary">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data(){
        var checkHeight = (rule, value, callback) => {
            var num = /^[0-9/]*$/
            if (!num.test(value)) {
                this.alterError = 1;
                return callback(new Error('身高格式有误'));
            }else{
                this.alterError = 0;
            }
        }
        var checkHeight = (rule, value, callback) => {
            var num = /^[0-9/]*$/
            if (!num.test(value)) {
                this.alterError = 1;
                return callback(new Error('身高格式有误'));
            }else{
                this.alterError = 0;
            }
        }
        var checkWeight = (rule, value, callback) => {
            var num = /^[0-9/]*$/
            if (!num.test(value)) {
                this.alterError = 1;
                return callback(new Error('体重格式有误'));
            }else{
                this.alterError = 0;
            }
        }
        var checkCardId= (rule, value, callback) => {
            if(value.length!=18){
                return callback(new Error('身份证信息格式有误'));
            }
        }
        return{
            isRewiriteEditor: false,//标志input框是否修改
            tableData:[],
            page:{
                currentPage: 1,  
                pageSize:5,
                total:0
            },
            isSearch:0,
            nowPatient:{
                patientId:0,
                patientName:"",
                patientMoney:0,
                patientHeight:0,
                patientWeight:""
            },
            dialogVisible:false,
            rules:{
                patientMoney:[
                    { required: true, message: '不能为空',  trigger: 'blur' }
                ],
                patientHeight:[
                    {  validator:checkHeight,  trigger: 'blur' }
                ],
                patientWeight:[
                    {  validator:checkWeight,  trigger: 'blur' }
                ],
            },
            // 搜索
            value:"",
            sort:2,
            text:'根据昵称搜索',
            errorSort:0,
            alterError:0,
            selectlistRow: [],
            dialogFormVisible: false,
            dialogVisible1:false,
            form:{
                name:"",
                age:0,
                phone:"",
                cardID:"",
                height:0,
                weight:0
            },
            // 添加用户信息的规则
            rules:{
                name:[
                    { required: true, message: '请输入姓名',  trigger: 'blur' }
                ],
                age:[
                    { required: true, message: '请输入年龄',  trigger: 'blur' }
                ],
                phone:[
                    { required: true, message: '请输入号码',  trigger: 'blur' }
                ],
                cardID:[
                    { required: true,validator: checkCardId,  trigger: 'blur' }
                ],
                height:[
                    { required: true,validator: checkHeight, trigger: 'blur' }
                ],
                weight:[
                    {required: true, validator: checkWeight, trigger: 'blur' }
                ],
            },
            radio: '1',
            formLabelWidth: '80px',
            fileList: []  

        }
    },
    created(){
        this.getAllPatient();
    },
    methods:{
        getAllPatient(){
            this.$axios.post(
                '/patient/getAllPatient',
                {
                    pageCurr:this.page.currentPage,  
                    pageSize:this.page.pageSize,
                }
            ).then(res =>{
                if(res != undefined){
                    if(res.code == 1){
                        console.log("用户列表",res)
                        this.tableData = res.data.list
                        this.page.total = res.data.totalSize
                    }else{
                        alert("服务器出错")
                    }                    
                }
            })
        },
        handleCurrentChange(newPage) {  
            // console.log(`当前页码变更为：${newPage}`);  
        //    在这里可以根据新的页码进行数据的加载或其他操作  
            this.page.currentPage = newPage; // 更新当前页码，如果需要进行页面数据更新的话  
        // 例如，你可能需要发送一个请求来获取新页码对应的数据  
            if(this.isSearch == 0){
                this.getAllPatient();
            }else if(this.isSearch == 1){
                this.searchInfo();
            }
        },
        // 获取表格选中时的数据
        selectRow (val) {
            this.selectlistRow = val
        },
        open(row) {
            this.$confirm('此操作将删除该用户信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                this.deletePatient(row);
            }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消删除'
            });          
            });
        },
        deletePatient(row){
            this.$axios.get(
                '/patient/deletePatient',
                {
                    params:{
                        patientId:row.patientId
                    }
                }
            ).then(res=>{
                if(res != undefined){
                    if(res.code == 1){
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                    }else if(res.code == -1){
                        this.$message.error(res.msg);
                    }else{
                        this.$message.error("删除失败");
                    }                    
                }
                console.log("删除用户",res)
                this.getAllPatient();
            })
        },
        alterClick(row) {
            this.nowPatient.patientId = row.patientId
            this.nowPatient.patientName = row.patientName
            this.nowPatient.patientMoney = row.patientMoney
            this.nowPatient.patientHeight = row.patientHeight
            this.nowPatient.patientWeight = row.patientWeight
            this.dialogVisible = true
        },
        cancel(){
            this.dialogVisible = false;
            this.getAllPatient();
        },
        sureCommit(){
            if(this.alterError != 1){
                this.$axios.get(
                    '/patient/alterInfo',
                    {
                        params:{
                            patientId:this.nowPatient.patientId,
                            patientMoney:this.nowPatient.patientMoney,
                            patientHeight:this.nowPatient.patientHeight,
                            patientWeight:this.nowPatient.patientWeight,
                        }
                    }
                ).then(res=>{
                    if(res != undefined){
                        console.log("修改用户信息",res)
                        if(res.code == 2){
                            this.$message({
                                showClose: true,
                                message: '暂未修改'
                            });
                        }else if(res.code == 1){
                            this.getAllPatient();
                            this.$message({
                                type: 'success',
                                message: '修改成功!'
                            })
                            this.dialogVisible = false;
                        }else{
                            alert("服务器出错，请稍后再来")
                        }                    
                    }
                })
            }
            
        },
        changSort(sort){
            this.sort = sort;
            if(sort == 1){
                this.text="id搜索,只能输入数字"
            }else if(sort == 2){
                this.text="根据昵称搜索"
            }else if(sort == 3){
                this.text="根据性别搜索(男/女)"
            }
        },
        returnAll(){
            this.isSearch = 0,
            this.value="";
            this.getAllPatient();
        },
        searchInfo(){
            this.isSearch = 1
            if(this.errorSort == 3){
                alert("请输入正确的性别信息")
                this.value = ""
            }else{
                this.$axios.get(
                    '/patient/selectByData',
                    {
                        params:{
                            sort:this.sort,
                            value:this.value,
                            pageCurr:this.page.currentPage,  
                            pageSize:this.page.pageSize,
                        }
                    }
                ).then(res =>{
                    if(res != undefined){
                        console.log("用户搜索",res)
                        this.tableData = res.data.list
                        this.page.total = res.data.totalSize
                    }
                    
                })
            }
            
        },
        inputChange(){
            if(this.sort == 1){
                this.value = this.value.replace(/[^\d]/g, '')
                this.errorSort = 0;
            }
            if(this.sort == 3){
                var six = /^[男|女]{1}$/;
                if(!six.test(this.value)){
                    this.errorSort = 3;
                }else{
                    this.errorSort = 0;
                }
            }
        },
        selectRow (val) {
            this.selectlistRow = val
        },
        delData () {
            var delPatientId = [];
            if(this.selectlistRow.length == 0){
                this.$message({
                    showClose: true,
                    message: '未选择要删除的人员'
                });
            }
            else{
                for (let i = 0; i < this.selectlistRow.length; i++) {
                    // 获取每个id---》到对应的去删除
                    let val = this.selectlistRow[i].patientId
                    delPatientId.push(val)
                }
                this.$axios.post(
                    '/patient/deleteUsers',
                    {
                        ids:delPatientId
                    }
                ).then(res=>{
                    if(res!=undefined){
                        if(res.code == 1){
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            })
                            this.getAllPatient();                       
                        }else{
                            this.$message({
                                showClose: true,
                                message: '修改失败',
                                type: 'error'
                            });
                        }
                    }
                })
            }
        },
        singleAdd(){
            this.dialogFormVisible = true;
        },
        // 重置表单内容
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        addCommit(){
            
            this.$axios.get(
                '/patient/addCommit',
                {
                    params:{
                        name:this.form.name,
                        age:this.form.age,
                        phone: this.form.phone,
                        cardID:this.form.cardID,
                        height:this.form.height,
                        weight:this.form.weight,
                        radio:this.radio
                    }
                }
            ).then(res=>{
                console.log(res)
                if(res != undefined){
                    if(res.code == 1){
                        this.$message({
                            message: '添加成功！',
                            type: 'success'
                        });
                        this.dialogFormVisible = false;
                        this.getAllPatient();
                        this.$refs["form"].resetFields();
                    }else if(res.code == 2){
                        this.$message.error('该用户已经注册过了');
                    }                    
                }

            })
        },
        handleSuccess(response, file, fileList) {  
            this.$message({
                showClose: true,
                message: '批量导入人员成功',
                type: 'success'
            }); 
            this.getAllPatient();
        },  
        beforeUpload(file) {  
            // 限制格式为excel
            // 如果不想限制可以将这行代码去掉，以及后面的一些关于excel的判断
            const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';  
            // 限制文件大小
            const isLt2M = file.size / 1024 / 1024 < 0.5;  

            if (!isExcel) {  
                this.$message.error('上传文件只能是 xls/xlsx 格式!');  
            }  

            if (!isLt2M) {  
                this.$message.error('上传文件大小不能超过 500KB!');  
            }  
            return isExcel && isLt2M;  
        },  
        submitUpload() {  
        // 这边的$refs.upload要与上面第三行的ref一致
            this.$refs.upload.submit();  
        },  
        handleRemove(file, fileList) {  
            console.log('移除文件', file, fileList);  
        },  
        handleChange(file, fileList) {  
            this.fileList = fileList;  
        },
        uploadVisible(){
            this.dialogVisible1 = true;
        },
        exportUser(){
            
            // this.$axios.get(
            //     "/admin/download",
            // ).then(res=>{
            //     this.$message({
            //         showClose: true,
            //         message: '导出成功',
            //         type: 'success'
            //     });
            // })
        }
    }
}
</script>
<style scoped>
.style-down a{
    text-decoration: none; 
    color: inherit;
}
.import-user a{
    text-decoration: none; 
    color: inherit;
}
.style-down{
   
    border-radius: 30px;
    border: none;
    height: 25px;
    float: right;
    width: 80px;
    margin-left: 5px;
    background-color: rgb(40, 113, 74);
    color:white;
    margin-top: -20px;
}
.style-down:hover{
    cursor: pointer;
    background-color:rgb(50, 190, 108);
}
.import-user{
    border-radius: 30px;
    border: none;
    height: 25px;
    float: right;
    width: 90px;
    margin-left: 5px;
    background-color: rgb(103, 42, 139);
    color:rgb(255, 255, 255);
    margin-top: -20px;
}
.import-user:hover{
    cursor: pointer;
    background-color:rgb(241, 79, 192);
}
.single-add{
    border-radius: 30px;
    border: none;
    height: 25px;
    float: right;
    width: 80px;
    margin-left: 5px;
    background-color: rgb(228, 116, 55);
    color:white;
    margin-top: -20px;
}
.single-add:hover{
    cursor: pointer;
    background-color:rgb(247, 166, 99);
}
@import "../../static/css/btnStyle.css"
</style>